<template>
    <div class="main-content">
        <div class="grid-container">
            <div 
                v-for="item in layoutSchema.defaultView.layout" 
                :key="item.id"
                class="grid-item"
                :style="{
                    gridColumn: `span ${getSpan(item.position.width)}`,
                    height: `${item.position.height}px`
                }"
            >
                <component
                    :is="getComponent(item.type, item)"
                    v-bind="getComponentProps(item)"
                />
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import BaseTable from './parts/BaseTable.vue';
import BaseChart from './parts/BaseChart.vue';
import BasePieChart from './parts/BasePieChart.vue';
import layoutSchema from '../json/layout-schema.json';

const loading = ref(false);
const tableData = ref([
    { id: 1, name: '张三', age: 25 },
    { id: 2, name: '李四', age: 35 },
    { id: 3, name: '王五', age: 15 },
    { id: 4, name: '赵六', age: 45 },
    { id: 5, name: '钱七', age: 28 }
]);

const chartData = ref({
    ageDistribution: {
        month: ["1月", "2月", "3月", "4月", "5月", "6月"],
        under18: [30, 32, 35, 34, 32, 30],
        age18to40: [120, 132, 135, 134, 132, 130],
        over40: [50, 52, 55, 54, 52, 50]
    },
    genderDistribution: {
        genderData: [
            { value: 335, name: '男性' },
            { value: 310, name: '女性' },
            { value: 234, name: '其他' }
        ]
    }
});

const getComponent = (type: string, item: any) => {
    const componentMap: Record<string, any> = {
        'table': BaseTable,
        'chart': item.config.chartType === 'pie' ? BasePieChart : BaseChart
    };
    return componentMap[type];
};

const getSpan = (width: string) => {
    // 将百分比转换为24栅格系统的span
    const percentage = parseInt(width);
    return Math.round((percentage / 100) * 24);
};

const getComponentProps = (item: any) => {
    const props: Record<string, any> = {
        loading: loading.value
    };

    if (item.type === 'table') {
        // 转换表格配置
        props.columns = item.config.fields.map((field: any) => ({
            prop: field.key,
            label: field.label,
            sortable: field.sortable
        }));
        props.dataSource = tableData.value;
    } else if (item.type === 'chart') {
        // 转换图表配置
        const data = chartData.value[item.config.dataKey];
        props.title = item.config.title;
        
        if (item.config.chartType === 'line') {
            props.option = {
                title: item.config.title,
                data: {
                    xAxis: data[item.config.xAxisKey],
                    series: item.config.seriesKeys.map((key: string) => ({
                        name: key === 'under18' ? '18岁以下' : 
                              key === 'age18to40' ? '18-40岁' : '40岁以上',
                        data: data[key]
                    }))
                }
            };
        } else if (item.config.chartType === 'pie') {
            props.option = {
                title: item.config.title,
                data: {
                    series: [{
                        type: 'pie',
                        radius: '50%',
                        data: data[item.config.seriesKey]
                    }]
                }
            };
        }
        
        props.height = item.position.height;
    }

    return props;
};

onMounted(async () => {
    loading.value = true;
    try {
        // 这里可以添加从API获取数据的逻辑
        // 例如：
        // const response = await fetch('/api/data');
        // const data = await response.json();
        // tableData.value = data.tableData;
        // chartData.value = data.chartData;
    } catch (error) {
        console.error('Failed to fetch data:', error);
    } finally {
        loading.value = false;
    }
});
</script>

<style scoped>
.main-content {
    padding: 20px;
}

.grid-container {
    display: grid;
    grid-template-columns: repeat(24, 1fr);
    gap: 20px;
}

.grid-item {
    min-height: 100px;
    background: white;
    border-radius: 4px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
    padding: 16px;
}
</style>